﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using CommDll;

namespace HospitalMedicineTraceability
{
    /// <summary>  
    /// ClassName:frmMain
    /// Version:1.0
    /// Date:2022-10-07
    /// Author:seanouyang
    /// </summary>  
    /// <remarks>  
    /// 本类是一WinForm 窗体,本窗体主要为系统主界面
    /// </remarks>
    public partial class frmMain : DevComponents.DotNetBar.RibbonForm
    {
        #region 01.自定义属性      
        #endregion

        /// <summary>
        /// 构造函数
        /// </summary>
        public frmMain()
        {
            InitializeComponent();
            // 分页Tab隐藏
            tabStrip1.Height = 0;
            //tabStrip1.Visible = false;
            // 01 设置窗体类别为 MDI
            this.IsMdiContainer = true;            
            // 02 设置窗体大小和位置
            this.Top = 0;
            this.Left = 0;
            this.Width = Screen.PrimaryScreen.WorkingArea.Width;
            this.Height = Screen.PrimaryScreen.WorkingArea.Height;
            // 03 相关信息初始化
            this.Icon = AppInfo.m_iconApp;
            this.Text = AppInfo.m_strAppName;   
            AppInfo.m_frmMain = this;  
        }

        #region 01.自定义方法
        /// <summary>
        /// 初始化系统功能
        /// </summary>
        private void _initSystemLimit()
        {
            // 01 保存所有功能项到m_dtFunction，在岗位设置中用（非系统功能）
            if (AppInfo.m_dtFunction == null)
            {
                AppInfo.m_dtFunction = new DataTable();
                AppInfo.m_dtFunction.Columns.Add("Code");
                AppInfo.m_dtFunction.Columns.Add("Name");
                AppInfo.m_dtFunction.Columns.Add("ParentCode");
                AppInfo.m_dtFunction.Columns.Add("ShowOrder");
            }
            else
            {
                AppInfo.m_dtFunction.Rows.Clear();
            }

            DataRow dr;
            //// 02 处理取所有的RibbonPanel           
            //foreach (Control control1 in ribbonControl1.Controls)
            //{
            //    // 非系统功能菜单
            //    if (control1.Name.Equals("ribbonPanel_System"))
            //    {
            //        continue;
            //    }
            //    string strName = control1.GetType().ToString();
            //    if (strName.Contains("RibbonPanel"))
            //    {
            //        // 功能组处理
            //        foreach (Control control in control1.Controls)
            //        {
            //            RibbonBar rb = ((RibbonBar)control);
            //            // 0201 加功能组信息
            //            dr = AppInfo.m_dtFunction.NewRow();
            //            dr["Code"] = rb.Name;
            //            dr["Name"] = rb.Tag;
            //            dr["ParentCode"] = "";
            //            dr["ShowOrder"] = rb.TabIndex;
            //            AppInfo.m_dtFunction.Rows.Add(dr);
            //            // 0202 加功能项信息
            //            foreach (BaseItem item in rb.Items)
            //            {
            //                dr = AppInfo.m_dtFunction.NewRow();
            //                dr["Code"] = item.Name;
            //                dr["Name"] = item.Text;
            //                dr["ParentCode"] = rb.Name;
            //                dr["ShowOrder"] = "";
            //                AppInfo.m_dtFunction.Rows.Add(dr);
            //            }
            //        }
            //    }
            //}

            // 03 增加非本系统功能查块(非Rti功能)
            //string strSql = "select * from TH_System_Module where not(KindCode like 'rti%') and Status = 1 order by KindCode,ShowOrder";
            string strSql = "select * from TH_System_Module where Status = 1 order by KindCode,ShowOrder";
            DataTable dt = AppInfo._openSql_DataTable(strSql);
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow dr0 in dt.Rows)
                {
                    // 增加主项
                    if (dr0["ShowOrder"].ToString().Equals("1"))
                    {
                        dr = AppInfo.m_dtFunction.NewRow();
                        dr["Code"] = dr0["KindCode"].ToString();
                        dr["Name"] = dr0["KindName"].ToString();
                        dr["ParentCode"] = "";
                        AppInfo.m_dtFunction.Rows.Add(dr);
                    }
                    // 增加子项
                    dr = AppInfo.m_dtFunction.NewRow();
                    dr["Code"] = dr0["Code"].ToString();
                    dr["Name"] = dr0["Name"].ToString();
                    dr["ParentCode"] = dr0["KindCode"].ToString();
                    AppInfo.m_dtFunction.Rows.Add(dr);
                }
            }
        }

        /// <summary>
        /// 初始化用户功能
        /// </summary>
        private void _initUserLimit()
        {
            // 00 admin 所有权限
            if (AppInfo.m_UserInfo.m_strRole.Contains("admin")) {
                return;
            }
            // 01 取所有的RibbonPanel           
            int nCountRibbonItem = 0;
            int nCountRibbonBar = 0;
            string strItemName = ""; // 功能项名称（当只有一项时用，设置间距）
            Dictionary<string, RibbonPanel> dictRibbonPanel = new Dictionary<string, RibbonPanel>();  //功能项

            foreach (Control control1 in ribbonControl1.Controls)
            {
                // 非系统功能菜单及隐藏功能
                //if (control1.Name.Equals("ribbonPanel_System") || !control1.Visible)
                if (control1.Name.Equals("ribbonPanel_System"))
                {
                    continue;
                }
                string strName = control1.GetType().ToString();
                if (strName.Contains("RibbonPanel"))
                {
                    nCountRibbonBar = 0;
                    foreach (Control control in control1.Controls)
                    {
                        nCountRibbonItem = 0;
                        // 非系统功能菜单及隐藏功能
                        if (!control.Name.Equals("rbSystem"))
                        {
                            RibbonBar rb = ((RibbonBar)control);
                            foreach (BaseItem item in rb.Items)
                            {
                                // 0201 按用户功能项过滤数据
                                item.Visible = (AppInfo.m_UserInfo.m_dictLimit).ContainsKey(item.Name);
                                if (item.Visible)
                                {
                                    nCountRibbonItem++;
                                }
                            }
                            // 最小功能组长度30
                            if (nCountRibbonItem == 1)
                            {
                                ((ButtonItem)((RibbonBar)control).Items[strItemName]).ImagePaddingHorizontal = 30;
                            }
                        }
                        // 0202 功能组是否可见
                        nCountRibbonBar += (nCountRibbonItem > 0) ? 1 : 0;
                    }
                    // 保存功能项
                    if (nCountRibbonBar > 0)
                    {
                        dictRibbonPanel.Add(control1.Name, (RibbonPanel)control1);
                    }
                }                
            }
            
            // 0203 RTI是否显示
            foreach (BaseItem item in this.ribbonControl1.Items) {
                // 非系统操作项判定，默认有
                if (!item.Name.Equals("rtiSystem"))
                {
                    item.Visible = dictRibbonPanel.ContainsKey(((RibbonTabItem)item).Panel.Name);
                }               
            }            
        }

        /// <summary>
        /// 判断是否有存在相同类窗体在tab页打开，防止打开多个同样的子窗体
        /// </summary>
        /// <param name="strTabName">窗体名称</param>
        /// <returns>如果存在返回true,否则返回false</returns>
        private bool _isTabOpen(string strTabName)
        {
            bool bIsOpened = false;
            // 01 显示子页面Tab
            if (tabStrip1.Height < 25)
            {
                tabStrip1.Height = 25;
                //tabStrip1.Visible = true;
                pbMain.Visible = false;
            }
            // 02 页循环比对页名称是否存在
            foreach (TabItem tabItem in tabStrip1.Tabs)
            {
                if (strTabName.Equals(tabItem.Text.Trim()))
                {
                    bIsOpened = true;
                    tabStrip1.SelectedTab = tabItem;
                    break;
                }
            }
            return bIsOpened;
        }

        /// <summary>
        /// 清除所有打开的tabs
        /// </summary>
        public void _clearTabs()
        {
            foreach (Form frmTemp in this.MdiChildren)
            {
                frmTemp.Close();
            }
        }

        /// <summary>
        /// 显示信息类窗体通用操作
        /// <param name="nKind">类别</param>
        private void _showQueryInfo(int nKind,string strInfo = "")
        {
            string tabName = strInfo;
            Form frm = new Form();
            if (!_isTabOpen(tabName))
            {
                switch (nKind)
                {
                    case 11:
                        frm = new frmDeptManage();
                        break;
                    case 12:
                        frm = new frmUserManage();
                        break;
                    case 13:
                        frm = new frmRoleManage();
                        break;
                    case 51:
                        frm = new frmQuery_EnterpriseCodeCheck();
                        break;
                    case 111:
                        frm = new frmQuery_CollectWarehouseStockIn();
                        ((frmQuery_CollectWarehouseStockIn)frm).m_nKind = 1;
                        break;
                    case 112:
                        frm = new frmQuery_CollectWarehouseStockIn();
                        ((frmQuery_CollectWarehouseStockIn)frm).m_nKind = 0;
                        break;
                    case 113:
                        frm = new frmQuery_CollectWarehouseStockIn();
                        ((frmQuery_CollectWarehouseStockIn)frm).m_nKind = 0;
                        break;
                    case 114:
                        frm = new frmTotal_CollectWarehouseStockIn();
                        break;                    
                    case 411:
                        frm = new frmQuery_CollectPharmacyStockOut();
                        ((frmQuery_CollectPharmacyStockOut)frm).m_nKind = 1;
                        break;
                    case 412:
                        frm = new frmQuery_CollectPharmacyStockOut();
                        ((frmQuery_CollectPharmacyStockOut)frm).m_nKind = 0;
                        break;
                    case 413:
                        frm = new frmQuery_CollectPharmacyStockOut();
                        ((frmQuery_CollectPharmacyStockOut)frm).m_nKind = 0;
                        break;
                    case 414:
                        frm = new frmTotal_CollectPharmacyStockOut();                        
                        break;
                    case 415:
                        frm = new frmQuery_SupervisionCodeSplit();
                        break;
                    case 511:
                        frm = new frmQuery_PlatformSupplierStockOut();
                        ((frmQuery_PlatformSupplierStockOut)frm).m_nKind = 0;
                        break;
                    case 512:
                        frm = new frmTotal_SupplierStockOut();
                        break;
                    case 513:
                        frm = new frmQuery_SupplierStockOutSupervisionCode();
                        break;
                    case 611:
                        frm = new frmQuery_GoodsTraceability();
                        break;
                    case 612:
                        frm = new frmQuery_SupervisionCode();
                        break;
                    case 613:
                        frm = new frmQuery_PatientTraceability();
                        break;
                    case 711:
                        frm = new frmQuery_GoodsCodeCheck();
                        break;
                    case 712:
                        frm = new frmQuery_GoodsSetup();
                        break;
                    case 811:
                        frm = new frmQuery_CollectPharmacyStockReturn();
                        ((frmQuery_CollectPharmacyStockReturn)frm).m_nKind = 1;
                        break;
                    case 812:
                        frm = new frmQuery_CollectPharmacyStockReturn();
                        ((frmQuery_CollectPharmacyStockReturn)frm).m_nKind = 0;
                        break;
                    case 813:
                        frm = new frmQuery_CollectPharmacyStockReturn();
                        ((frmQuery_CollectPharmacyStockReturn)frm).m_nKind = 0;
                        break;
                    case 814:
                        frm = new frmTotal_CollectPharmacyStockReturn();
                        break;
                }
                frm.Text = string.Format(" {0} ", tabName);
                frm.MdiParent = this;
                frm.WindowState = FormWindowState.Maximized;
                frm.Show();
            }
        }
       
        /// <summary>
        /// 系统登录
        /// </summary>
        private void _login()
        {
            // 01 登录窗体
            frmLogin frm = new frmLogin();
            frm.m_bReLogin = true;
            frm.ShowIcon = true;
            frm.ShowInTaskbar = false;
            frm.TopMost = true;
            frm.ShowDialog();
            // 02 登录成功,重新初始化,打开主页面FrmMain，否则退出系统
            if (AppInfo.m_bLogin)
            {
                AppInfo.m_bLogin = false;
                this.Close();
                //_clearTabs();
                //this.Text = string.Format("{0}【单位名称:{1}({2})-{3}】", AppInfo.m_strAppName, AppInfo.m_UserInfo.m_strDeptName, AppInfo.m_UserInfo.m_strDeptCode, AppInfo.m_UserInfo.m_strName);
                //this.RibbonControl.TitleText = this.Text;                
            }
            else
            {
                AppInfo.m_bLogin = true;                
            }
        }
        #endregion  

        #region 02.系统窗体控件事件方法
        
        private void frmMain_Load(object sender, EventArgs e)
        {
            // 04 初始化系统功能(重新登录不处理)
            if (AppInfo.m_dtFunction == null)
            {
                _initSystemLimit();
            }
            // 00 用户权限
            _initUserLimit();
            // 01 初始化登录员
            this.Text = string.Format("{0}【单位名称:{1}({2})-{3}】_Ver{4}", AppInfo.m_strAppName, AppInfo.m_UserInfo.m_strDeptName, AppInfo.m_UserInfo.m_strDeptCode, AppInfo.m_UserInfo.m_strName,AppInfo.m_strAppVer);
            this.RibbonControl.TitleText = this.Text;
            this.rtiSystem.Checked = true;
        }

        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            // 如果未登录，不进行退出提示
            if (AppInfo.m_bLogin)
            {
                DialogResult result = CommFun._messageBoxShow("是否确定退出本系统?", "系统提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (result == DialogResult.Yes)
                {
                    this.Dispose();
                }
                else
                {
                    e.Cancel = true;
                }
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            // 计时处理，显示时间在statusBar上
            lblDatetime.Text = string.Format("当前时间:{0}", DateTime.Now.ToString("yyyy年MM月dd日 HH:mm:ss"));
        }

        private void tabStrip1_TabRemoved(object sender, EventArgs e)
        {
            // 01 Tab页关闭完所有页后显示主页图片
            if (tabStrip1.Tabs.Count == 0)
            {
                tabStrip1.Height = 0;
                //tabStrip1.Visible = false;
                pbMain.Visible = true;
            }
        }

        private void rti_CheckedChanged(object sender, EventArgs e)
        {
            // 功能菜单切换，加上系统功能栏
            rbSystem.Left = 1000;   // 需加上，不然会到前面位置
            ((DevComponents.DotNetBar.RibbonTabItem)sender).Panel.Controls.Add(rbSystem);
        }

        #endregion

        #region 03.菜单功能项:系统操作
 
        private void biSetup_Click(object sender, EventArgs e)
        {
            // 系统设置
            frmSetup frm = new frmSetup();
            frm.ShowIcon = true;
            frm.ShowInTaskbar = false;
            frm.ShowDialog();
        }

        private void biSystem_PasswordChange_Click(object sender, EventArgs e)
        {
            // 修改口令
            frmPasswordChange frm = new frmPasswordChange();
            frm.ShowIcon = true;
            frm.ShowInTaskbar = false;
            frm.ShowDialog();
        }

        private void biSystem_About_Click(object sender, EventArgs e)
        {
            // 关于
            frmAbout frm = new frmAbout();
            frm.ShowIcon = true;
            frm.ShowInTaskbar = false;
            frm.TopMost = true;
            frm.ShowDialog();
        }

        private void biSystem_Logout_Click(object sender, EventArgs e)
        {
            // 01 系统注销
            DialogResult result = CommFun._messageBoxShow("是否确定要注销当前用户?", "系统提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (result == DialogResult.No)
            {
                return;
            }
            // 02 重新进行登录
            _login();
        }

        private void biSystem_Exit_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        #endregion
        
        #region 04.菜单功能项业务操作        
        private void biButtomItem_Click(object sender, EventArgs e)
        {
            // 显示通用子窗体,按按钮的Tag号处理,名称为上一级RibbonBar名称+按钮名称
            ButtonItem bi = (ButtonItem)sender;
            string strName = string.Format("{0}->{1}", ((RibbonBar)bi.ContainerControl).Tag.ToString(), bi.Text);
            int nKind = (bi.Tag == null) ? 0 : FunctionComm._strToInt(bi.Tag.ToString());
            _showQueryInfo(nKind, strName);
        }
        #endregion

        private void frmMain_Shown(object sender, EventArgs e)
        {
            
        }

        private void frmMain_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Alt && e.KeyCode == Keys.M)
            {
                this.WindowState = (this.WindowState == FormWindowState.Minimized)? FormWindowState.Normal: FormWindowState.Minimized;
            }            
        }

        private void toolStripMenuItemMin_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
        }

        private void toolStripMenuItemMax_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Maximized;
        }

        private void ToolStripMenuItem_Show_Click(object sender, EventArgs e)
        {
            WindowState = FormWindowState.Normal;
        }

        private void ribbonControl1_DoubleClick(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
        }

        private void rbSystem_DoubleClick(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Maximized;
        }

        private void rbSystem_ItemClick(object sender, EventArgs e)
        {

        }
    }
}